package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.dpl.entity.report.QueryField;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.dpl.vo.QueryFieldType;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryConstants;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryParamHolder;
import com.mallcai.bigdata.ladon.service.report.impl.handler.support.ParamValueConverter;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 这个规则,用来合并数据库中配置的参数和用户调用时的参数
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 21:03
 */
@Slf4j
@Component
@Order(4000)
public class MergeQueryParamHandler extends AbstractReportQueryPreHandler {

    @Override
    public void preInternal(ReportQueryContext context) {
        Set<String> allParams = context.getInnerParam(ReportQueryConstants.KEY_ALL_PARAM_NAME);
        // sql不需要参数则直接到下一个handler
        if (CollectionUtils.isEmpty(allParams)){
            return;
        }
        List<QueryField> queryFields = context.getInnerParam(ReportQueryConstants.KEY_QUERY_FIELDS);
        Map<String, Object> originalParams = context.getOriginalParams();

        queryFields.forEach(queryField -> {
            if(allParams.contains(queryField.getQueryName())){
                Object value = originalParams.get(queryField.getQueryName());
                DataType dataType = DataType.getByCode(queryField.getDataType());
                if (dataType == null){
                    throw new BusinessException(String.format("不支持的参数类型[%s]", queryField.getDataType()));
                }
                if(value == null && StringUtils.isNotEmpty(queryField.getValDefault())){
                    value = ParamValueConverter.convert(queryField.getValDefault(), dataType,
                            QueryFieldType.MULTIPLE.isSupport(queryField.getType())) ;
                }
                ReportQueryParamHolder paramHolder = ReportQueryParamHolder.createInstance(queryField.getQueryName(), value,
                        dataType, queryField.getType());
                context.putQueryParam(queryField.getQueryName(), paramHolder);
            }
        });
    }

}
